<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '修改商品' : '添加商品' }}</span>
      </template>

      <el-card shadow="never">

        <div class="flex-column-between">
          <el-form ref="form"
                   :model="form"
                   :rules="rules"
                   label-width="100px">
            <el-form-item label="商品标题:"
                          prop="name">
              <el-input clearable
                        :maxlength="100"
                        v-model="form.name"
                        placeholder="请输入商品标题">
              </el-input>
            </el-form-item>

            <!-- 提交图片 -->
            <el-form-item label="上传商品图片:"
                          prop="img">
              <el-upload action="#"
                         :on-exceed="exceedFn"
                         list-type="picture-card"
                         :file-list="fileList"
                         :limit="5"
                         :on-change="
                  (files, fileList) => handleFileChange(files, fileList)
                "
                         :auto-upload="false">
                <i slot="default"
                   class="el-icon-plus"></i>
                <div slot="file"
                     slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail"
                       :src="file.url"
                       alt="" />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview()">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete"
                          @click="handleDownload(file)">
                      <i class="el-icon-download"></i>
                    </span>
                    <span class="el-upload-list__item-delete"
                          @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
            </el-form-item>
            <!-- 商品付标题 -->
            <el-form-item label="商品副标题:"
                          prop="title">
              <el-input clearable
                        :maxlength="100"
                        v-model="form.title"
                        placeholder="请输入商品副标题">
              </el-input>
            </el-form-item>
            <!-- 选择分类 -->
            <el-form-item label="所属分类:"
                          prop="classify_id">
              <el-select clearable
                         class="ele-block"
                         v-model="form.classify_id"
                         @visible-change="(event) => getCategoriesList(event)"
                         placeholder="请选择所属分类">
                <el-option v-for="(item, index) in serviceCategoriesList"
                           :key="index"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 商品模式 -->
            <!-- <el-form-item label="商品模式:"
                          prop="sale_mode">
              <el-select v-model="form.sale_mode"
                         placeholder="请选择商品模式">
                <el-option v-for="item in options"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item> -->
            <!-- 发货时间 -->
            <el-form-item label="发货时间:"
                          prop="delivery_time">
              <el-select v-model="form.delivery_time"
                         placeholder="请选择商品模式">
                <el-option v-for="item in deliveryTimeList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 是否为积分购买 -->
            <el-form-item label="是否积分抵扣:"
                          prop="buying_pattern">
              <el-switch :active-value="1"
                         :inactive-value="2"
                         v-model="form.buying_pattern" />
            </el-form-item>
            <!--售卖价  -->
            <el-form-item label="售卖价:"
                          prop="price">
              <el-input clearable
                        type="number"
                        v-model="form.price"
                        placeholder="请输入售卖价">
              </el-input>
            </el-form-item>
            <!--市场价  -->
            <el-form-item label="市场价:"
                          prop="market_price">
              <el-input clearable
                        type="number"
                        v-model="form.market_price"
                        placeholder="请输入市场价">
              </el-input>
            </el-form-item>

            <el-form-item>
              <div style="margin-bottom: 10px;">
                <div>
                  <span style="font-weight: 700;margin-right: 5px;">是否开启会员等级</span>
                  <el-switch :active-value="1"
                             :inactive-value="0"
                             @change="MembershipLevelFn"
                             v-model="form.is_swich_level" />
                </div>
                <span style="color: red;">如果开启将会针对单个商品的的折扣</span>
              </div>
              <!-- 选择会员等级 -->

              <div v-if="form.is_swich_level==1">
                <div v-for="(i, index) in form.discount"
                     :key="index"
                     class="myNmae flex-between margin-top_40rpx m-bottom15">
                  <div class="font-weight_bold">
                    <el-dropdown @command="(e) => handleCommand(e, index)">
                      <span class="el-dropdown-link">
                        {{ i.level
                      }}<i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item v-for="(item, iw) in levelList"
                                          :key="iw"
                                          :command="item">{{ item.text }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                  <div class="flex">
                    <el-input class="uni-input"
                              type="number"
                              v-model="i.discount"
                              placeholder="请填写折扣价">
                      <template slot="append">%</template></el-input>

                    <div class="margin-left_10rpx">
                      <el-button class="mini-btn"
                                 @click="add()"
                                 v-if="0 == index"
                                 type="primary">+</el-button>

                      <el-button type="primary"
                                 class="mini-btn"
                                 @click="subtract(index)"
                                 v-else>-</el-button>
                    </div>
                  </div>
                </div>
                <span style="color: rgb(255, 0, 0);">备注：以百分比形式(如填写95等于购买商品享受9.5折优惠)</span>
              </div>
            </el-form-item>

            <!-- 库存 -->
            <el-form-item label="库存:"
                          prop="inventory">
              <el-input clearable
                        type="number"
                        :maxlength="100"
                        v-model="form.inventory"
                        placeholder="请输入库存">
              </el-input>
            </el-form-item>
            <!-- 商品详情 -->
            <el-form-item label="商品详情:"
                          prop="desc">
              <tinymce-editor v-model="form.desc"
                              :init="editorConfig" />
            </el-form-item>
          </el-form>
          <div class="drawer__footer">
            <el-button round
                       type="plain"
                       @click="handleClose"
                       size="medium">返回</el-button>
            <el-button type="primary"
                       round
                       :loading="loading"
                       size="medium"
                       @click="save">确定</el-button>
          </div>
        </div>
      </el-card>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import TinymceEditor from '@/components/TinymceEditor/index.vue';

import { upload } from '@/api/saveImg/index';
import { levelList, goodsInfo, addGoods, editGoods } from '@/api/goods/index';
import { classifyList } from '@/api/classifyList/index';

export default {
  name: 'pictureEdit',
  components: { ElImageViewer, TinymceEditor },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const categoryImage = (rule, value, callback) => {
      console.log(this.form.host_img);
      if (!this.form.host_img) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 商品名称

      name: '',
      // 商品图片
      host_img: [],
      // 商品详情
      desc: '',

      // 发货时间
      delivery_time: '',
      // 价格
      price: '',
      // 市场价格
      market_price: '',
      // 分类id
      classify_id: '',
      // 商品模式 1现货 2 预售
      is_swich_level: 1,
      //   sale_mode: '',
      // 是否积分购买 1允许 2 不允许
      buying_pattern: '2',
      // 库存
      inventory: '',
      title: '',
      // 折扣
      discount: [
        {
          level_id: '',
          discount: '',
          level: '选择会员等级'
        }
      ]
    };
    return {

      editorConfig: {
        height: 525,
        relative_urls: false,
        convert_urls: false,

        images_upload_handler: async (blobInfo, success) => {
          //  ==================================

          const files = blobInfo.blob();
          // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
          const param = new FormData();

          param.append('file', files, files.name);

          const res = await upload(param);
          console.log(res.data.url);

          success(res.data.url);

          // });
        }
      },
      // 是否开启会员等级
      isMembershipLevel: 1,
      options: [
        {
          value: 1,
          label: '现货'
        },
        {
          value: 2,
          label: '预售'
        }
      ],
      deliveryTimeList: [
        {
          value: '24小时',
          label: '24小时'
        },
        {
          value: '48小时',
          label: '48小时'
        },
        {
          value: '72小时',
          label: '72小时'
        }
      ],
      storageMode: '',

      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      serviceCategoriesList: [],
      // 会员列表
      levelList: [],
      // 表单验证规则
      rules: {
        inventory: [
          {
            required: true,
            message: '请输入库存',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入售卖价',
            trigger: 'blur'
          }
        ],
        market_price: [
          {
            required: true,
            message: '请输入市场价',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ],
        classify_id: [
          {
            required: true,
            message: '请选择分类名称',
            trigger: 'blur'
          }
        ],
        delivery_time: [
          {
            required: true,
            message: '请选择发货时间',
            trigger: 'blur'
          }
        ],
        // sale_mode: [
        //   {
        //     required: true,
        //     message: '请选择商品模式',
        //     trigger: 'blur'
        //   }
        // ],

        // title: [
        //   {
        //     required: true,
        //     message: '请输入商品副标题',
        //     trigger: 'blur'
        //   }
        // ],
        // desc: [
        //   {
        //     required: true,
        //     message: '请输入商品详情',
        //     trigger: 'blur'
        //   }
        // ],
        sort: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        img: [{ required: true, validator: categoryImage, trigger: 'change' }]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  mounted () {
    this.levelListFn();
  },
  methods: {
    MembershipLevelFn (e) {
      // 0 开启 1 关闭
      console.log(e)
      this.form.is_swich_level = e
    },
    // 商品详情接口 获取会员等级
    async goodsInfoFn (id) {
      const result = await goodsInfo({
        id: id
      });

      if (result.code == 0) {
        console.log(result);
        if (result.data.discount.length) {
          this.form.discount = result.data.discount;
          if (this.levelList.length) {
            this.form.discount = result.data.discount.map((item) => {
              const levelType = this.levelList.find((items) => {
                return items.value == item.level_id;
              });

              return {
                discount: item.discount,
                level_id: item.level_id,
                level: levelType.text,
                create_time: item.create_time,
                goods_id: item.goods_id,
                id: item.id,
                update_time: item.update_time
              };
            });
            console.log(this.form.discount);
          }
        } else {
          this.form.discount = [
            {
              level_id: '',
              discount: '',
              level: '选择会员等级'
            }
          ];
        }
      } else {
        this.$sun.toast(result.msg, 'none');
      }
    },

    handleCommand (e, index) {
      console.log(e, index);
      this.form.discount[index].level_id = e.value;
      this.form.discount[index].level = e.text;
    },
    async getCategoriesList () {
      const res = await classifyList({
        limit: 10,
        page: 1
      });
      const agentList = res.list.map((item) => {
        return {
          label: item.name,
          value: item.id
        };
      });
      console.log(agentList);

      this.serviceCategoriesList = agentList;
    },
    async levelListFn () {

      const res = await levelList();
      console.log(res);
      if (res.code == 0) {
        const classifyData = res.data.list.map((item) => {
          return {
            text: item.name,
            value: item.id
          };
        });
        this.levelList = classifyData;

        console.log(this.levelList);
        if (this.isUpdate) {
          this.goodsInfoFn(this.form.id);
        }
      }
    },
    // 获取存储配置
    // async storageConfig () {
    //   const res = await storageConfigDetail();

    //   // console.log(res.storageMode);

    //   this.storageMode = res?.storageMode;
    // },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove (file) {
      console.log(file);
      const findIndex = this.fileList.findIndex((item) => {
        return item.url == file.url;
      });
      console.log(findIndex);
      this.fileList.splice(findIndex, 1);
      this.form.host_img.splice(findIndex, 1);
      //   this.fileList = [];
      //   this.imageUrl = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file) {
      this.loading = true;
      console.log(this.storageMode);
      let files = file.raw;

      let param = new FormData();
      param.append('file', files, files.name);
      const res = await upload(param);
      console.log(res);
      if (res.code == 0) {
        this.loading = false;
        let markIndex = res.data.url.lastIndexOf('.');
        let suffix = res.data.url.substring(markIndex);
        this.fileList.push({
          name: suffix,
          url: res.data.url
        });
        this.form.host_img.push(res.data.url);

      }
    },

    // 点击按钮预览图片

    handlePictureCardPreview () {

      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    // 添加字幕
    add () {

      // 这里需要判断等下如果 超出会员等级列表那么就不能添加
      if (this.form.discount.length >= this.levelList.length) {
        this.$message.success('添加会员等级已经到达上限')
        return false
      }
      let content = {
        discount: '',
        level_id: '',
        level: '选择会员等级'
      };
      this.form.discount.push(content);
      console.log(
        'this.form.discount',
        this.form.discount,
        this.form.discount.length
      );
    },
    //删除字幕
    subtract (index) {
      this.form.discount.splice(index, 1);
      console.log(
        'this.form.discount',
        this.form.discount,
        this.form.discount.length
      );
    },
    customLogic (a, b) {
      if (!a && !b) {
        return true; // 两个都是 false
      } else if (a && b) {
        return true; // 两个都是 true
      } else {
        return false; // 至少有一个是 false
      }
    },
    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }

        // localStorage.setItem('isMembershipLevel', JSON.stringify(this.isMembershipLevel)); // 存储 “系统图标等”
        // eslint-disable-next-line no-unused-vars
        let discountsWithoutLevel = this.form.discount.map(
          // eslint-disable-next-line no-unused-vars
          ({ level, ...rest }) => rest
        );
        console.log(discountsWithoutLevel.length)
        if (discountsWithoutLevel.length) {
          for (let i = 0; i < discountsWithoutLevel.length; i++) {
            const item = discountsWithoutLevel[i];
            console.log(this.form.is_swich_level)
            if ((this.form.is_swich_level == 1)) {
              if (!item.level_id) {
                this.$message.error('请填写会员等级');
                return; // 提前结束循环并返回
              }
              if (!item.discount) {
                this.$message.error('请填写折扣价');
                return; // 提前结束循环并返回
              }
            } else {
              //   this.$message.error('会员等级折扣价都没填');
              discountsWithoutLevel = []

            }
            // 其他逻辑

          }
        } else {
          for (let i = 0; i < discountsWithoutLevel.length; i++) {
            const item = discountsWithoutLevel[i];

            if (!this.customLogic(item.level_id, item.discount)) {
              this.$message.error('请填写会员等级或者折扣价');
              return; // 提前结束循环并返回
            }

            // 其他逻辑
          }
        }
        this.form.discount = discountsWithoutLevel;
        this.form.host_img = this.form.host_img.join(',');
        const data = {
          ...this.form
        };

        console.log(data);
        this.loading = true;

        const saveOrUpdate = this.isUpdate ? editGoods : addGoods;
        saveOrUpdate(data)
          .then((msg) => {
            this.fileList = [];
            console.log(msg);
            this.loading = false;
            this.$message.success(msg.message);

            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {

      this.$nextTick(() => {
        this.loading = false;
        if (visible) {
          this.imageUrl = ''
          console.log(this.data);
          if (this.data) {
            this.form.host_img = []
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });
            if (this.data.host_img.length) {
              console.log(this.form.host_img);
              this.imageUrl = this.data.host_img.join(',')

              this.data.host_img.forEach((item) => {

                let markIndex = item.lastIndexOf('.');
                let suffix = item.substring(markIndex);
                this.fileList.push({
                  name: suffix,
                  url: item
                });
              });
              console.log(this.form);
            } else {
              this.fileList = [];
            }
            // this.isMembershipLevel = JSON.parse(localStorage.getItem('isMembershipLevel'));
            this.isUpdate = true;
            this.getCategoriesList();
            this.levelListFn();
          } else {
            this.isUpdate = false;
            this.form.host_img = []
            this.form.discount = [
              {
                level_id: '',
                discount: '',
                level: '选择会员等级'
              }
            ];
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
/deep/.el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}
/deep/.el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}

/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
